<template>
  <div id="spaceManagePage">
    <!-- 搜索表单区域 -->
    <!-- 使用 a-form 组件创建一个高级搜索表单，并绑定 model 属性到 searchForm 对象上 -->
    <a-form
      ref="formRef"
      name="advanced_search"
      layout="inline"
      :model="searchQueryParams"
      @finish="handleSearch"
    >
      <a-form-item name="spaceName" label="空间名称">
        <a-input v-model:value="searchQueryParams.spaceName" placeholder="请输入空间名称"></a-input>
      </a-form-item>
      <a-form-item name="spaceLevel" label="空间级别">
        <a-select
          v-model:value="searchQueryParams.spaceLevel"
          placeholder="请选择或输入空间级别"
          :options="SPACE_LEVEL_OPTIONS"
          allowClear
          style="min-width: 180px"
        />
      </a-form-item>
      <a-form-item label="空间类别" name="spaceType">
        <a-select
          v-model:value="searchQueryParams.spaceType"
          :options="SPACE_TYPE_OPTIONS"
          placeholder="请输入空间类别"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>
      <a-form-item name="userId" label="用户 id">
        <a-input v-model:value="searchQueryParams.userId" placeholder="请输入用户 id"></a-input>
      </a-form-item>
      <a-form-item>
        <!-- 查询按钮、重置按钮 -->
        <a-button type="primary" html-type="submit">查询</a-button>
        <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
      </a-form-item>
    </a-form>

    <a-divider></a-divider>
    <!-- 按钮位置 -->
    <div class="buttons">
      <a-space>
        <a-button
          type="primary"
          :disabled="selectRowKeys.length <= 0"
          :loading="deleteLoading"
          @click="handleBatchDelete"
        >
          批量删除
        </a-button>
        <a-button type="primary" href="/add_space" target="_blank">+ 创建空间</a-button>
        <a-button type="primary" ghost href="/space_analyze?queryPublic=1" target="_blank">
          分析公共图库
        </a-button>
        <a-button type="primary" ghost href="/space_analyze?queryAll=1" target="_blank">
          分析全空间
        </a-button>
      </a-space>
    </div>

    <!-- 用户表格区域 -->
    <!-- 使用 a-table 组件展示用户列表数据  配置rowSelection选择框的时候 一定要同时配置 rowKey行的唯一键 不然会出现各种问题:例如:选中一行会导致所有行被选中-->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      :row-selection="rowSelection"
      rowKey="id"
      bordered
      :scroll="{ x: 'max-content' }"
    >
      <!-- 定义表格中单元格的内容 -->
      <template #bodyCell="{ column, record }">
        <!-- 空间级别 -->
        <template v-if="column.dataIndex === 'spaceLevel'">
          <a-tag>{{ SPACE_LEVEL_MAP[record.spaceLevel] }}</a-tag>
        </template>
        <!-- 空间类别 -->
        <template v-if="column.dataIndex === 'spaceType'">
          <a-tag>{{ SPACE_TYPE_MAP[record.spaceType] }}</a-tag>
        </template>

        <!-- 使用情况 -->
        <template v-if="column.dataIndex === 'spaceUseInfo'">
          <div>大小：{{ formatSize(record.totalSize) }} / {{ formatSize(record.maxSize) }}</div>
          <div>数量：{{ record.totalCount }} / {{ record.maxCount }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button size="small" type="link" :href="`/add_space?id=${record.id}`" target="_blank">
              编辑
            </a-button>
            <a-dropdown>
              <a-button size="small" type="link">
                更多
                <DownOutlined />
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1">
                    <a-popconfirm
                      title="您确定要删除这个数据吗?"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="() => handleDelete(record.id)"
                    >
                      <a-button type="link" danger> 删除</a-button>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item key="2">
                    <a-button
                      type="link"
                      :href="`/space_analyze?spaceId=${record.id}`"
                      target="_blank"
                    >
                      分析
                    </a-button>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, createVNode, onMounted, reactive, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { listPictureTagCategoryUsingGet } from '@/api/pictureController.ts'
import {
  deleteBatchSpaceUsingPost,
  deleteSpaceUsingPost,
  listSpaceByPageUsingPost,
} from '@/api/spaceController.ts'
import { columns } from '@/pages/admin/space/spaceManagePage.data.ts'
import {
  SPACE_LEVEL_MAP,
  SPACE_LEVEL_OPTIONS,
  SPACE_TYPE_MAP,
  SPACE_TYPE_OPTIONS,
} from '../../../constants/space.ts'
import { formatSize } from '../../../utils'

// 定义数据列表和总数变量，用于存储从后端获取的用户数据和总记录数
const dataList = ref([])
const total = ref(0)

// 定义选中的行的键值数组和选中的行数组，用于批量操作
const selectRowKeys = ref<number[]>([])
const selectRows = ref([])

// 计算属性：定义表格行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectRowKeys.value,
  onChange: (selectedKeys: number[], selectedRows: any[]) => {
    selectRowKeys.value = selectedKeys
    selectRows.value = selectedRows
  },
}))

// 定义查询参数对象，用于分页及搜索条件传递给后端接口
const searchQueryParams = reactive<API.SpaceQueryRequest>({
  pageNum: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'dsc',
})

// 计算属性：定义分页器配置
const pagination = computed(() => ({
  current: searchQueryParams.pageNum,
  pageSize: searchQueryParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  onChange: (pageNum: number, pageSize: number) => {
    searchQueryParams.pageNum = pageNum
    searchQueryParams.pageSize = pageSize
    searchList()
  },
  showTotal: (total: number) => `共 ${total} 条数据`,
}))

// 查询用户列表：根据当前的查询参数向后端请求用户数据
const searchList = async () => {
  const res = await listSpaceByPageUsingPost(searchQueryParams)
  if (res.code === 0 && res.data) {
    dataList.value = res.data.records
    total.value = Number(res.data.total)
  }
}

// 处理搜索逻辑：将搜索表单的数据合并到查询参数中并调用 searchList 函数加载数据
const handleSearch = () => {
  searchList()
}
// 重置搜索逻辑：清空搜索表单和查询参数，并重新加载数据
const resetSearch = () => {
  resetQueryParams()
  searchList()
}
const formRef = ref()
// 通用重置函数
const resetQueryParams = () => {
  // 使用表单自带的resetFields方法
  formRef.value.resetFields()
  selectRowKeys.value = []
  selectRows.value = []
  searchQueryParams.pageNum = 1
  searchQueryParams.pageSize = 10
  searchQueryParams.sortField = 'createTime'
  searchQueryParams.sortOrder = 'dsc'
}

// 删除单个
const handleDelete = async (id: string) => {
  try {
    const res = await deleteSpaceUsingPost({ id })
    if (res.code === 0) {
      message.success('删除成功')
      await resetSearch()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

const deleteLoading = ref(false)
const handleBatchDelete = async () => {
  Modal.confirm({
    title: '您确定要删除选中的数据吗？',
    icon: createVNode(ExclamationCircleOutlined),
    content: '',
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      deleteLoading.value = true
      try {
        const res = await deleteBatchSpaceUsingPost(selectRowKeys.value)
        if (res.code === 0) {
          message.success('删除成功')
          resetSearch()
        } else {
          message.error('删除失败')
        }
      } finally {
        deleteLoading.value = false
      }
    },
    onCancel() {
      deleteLoading.value = false
      console.log('Cancel')
    },
  })
}

// 页面加载完成后自动执行一次查询以初始化用户列表
onMounted(() => {
  searchList()
})

// 分类和标签选项列表
const tagsOptions = ref<{ label: string; value: string }[]>([])
const categoryOptions = ref<{ label: string; value: string }[]>([])

/**
 * 获取所有可用的分类和标签选项。
 * 这些选项用于填充分类选择框和标签选择框。
 */
const fetchCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.code === 0 && res.data) {
    tagsOptions.value = res.data.tagList.map((item: string) => ({ label: item, value: item }))
    categoryOptions.value = res.data.categoryList.map((item: string) => ({
      label: item,
      value: item,
    }))
  }
}
onMounted(() => {
  fetchCategoryOptions()
})
</script>

<style scoped>
/* 可以根据需要添加更多样式 */
</style>
